package com.example.sample.activity;

import com.example.app.BaseActivity;
import com.example.sample.R;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import net.liteheaven.xblib.common.res.AssetUtil;

/**
 * 
 * 演示webView如何和js交互等
 * 
 * 
 * 使用javascript调用android代码的步骤：
 * 1.使用webview对象的addJavascriptInterface方法
 * 2.addJavascriptInterface方法有两个参数，第一个参数就是我们一般会实现一个自己的类，类里面提供我们要提供给javascript访问的方法；
 * 第二个参数是访问我们在obj中声明的方法时候所用到的js对象，
 * 调用模式为window.interfaceName.方法名()或者是javascript: interfaceName.方法名() ;，
 * 如myWebView.addJavascriptInterface(new JavaScriptInterface(this), "android");	
 * 3.编写JavaScriptinterface类，如有一个函数名为showToast()的方法
 * 4.在html中调用时的形式：javascript：android.showToast()。
 * 
 * @author  LiangYu
 * @data:  2015-10-21 下午6:17:31
 */
public class WebViewActivity extends BaseActivity {

	private static final String URL_DOWNLOAD = "https://download.pingan.com.cn/app/android/CFB-PINGAN-v2.2.7.apk";
	// 齐若彤要刷的网页
	// private static final String URL_LOAD = "https://mp.weixin.qq.com/s/bwwoybI88eQgiZhpIx29rg";
	// QQ
	private static final String URL_LOAD = "https://www.baidu.com";

	private static final String TAG = "WebViewActivity";
	private WebView mWebView;
	private View btnLoadBySys;
	private View btnLoad;
	private View btnDown;
	private View btnLoadPage;
	private Handler handler = new Handler();
	
	/**
	 * 
	 * 网页客户端类 
	 * @author  LiangYu
	 * @data:  2015-10-21 下午6:26:15
	 */
	public static class MyWebViewClient extends WebViewClient{
		
		private Context context;
		
		public MyWebViewClient(Context context){
			this.context = context;
		}
		
		@Override  
	    public boolean shouldOverrideUrlLoading(WebView view, String url) {
	    	Log.i(TAG, "shouldOverrideUrlLoading " + url);
	        //设置点击网页里面的链接还是在当前的webview里跳转  
	        view.loadUrl(url);
			return super.shouldOverrideUrlLoading(view, url);
	    }     
	    @Override
	    public void onReceivedSslError(WebView view,
	    		SslErrorHandler handler, SslError error) {
	    	Log.i(TAG, "onReceivedSslError");
	    	//设置webview处理https请求  
	        handler.proceed();
	    } 
	    public void onReceivedError(WebView view,  
	            int errorCode, String description, String failingUrl) {  
	    	Log.i(TAG, "onReceivedError " + failingUrl);
	        //加载页面报错时的处理  
	        Toast.makeText(context, "Oh no! " + description, Toast.LENGTH_SHORT).show();  
	    }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Log.i(TAG, "onReceivedError " + request.getUrl());
            }
        }
    }

	public static class JavaScriptInterface{
		
		private Context mContext;

	    public JavaScriptInterface(Context c) {
	        mContext = c;
	    }

	    /**
	     * 注：如果将targetSdkVersion 设置为17或者更高，但却没有给暴露的js接口加@JavascriptInterface注释，则logcat会报如下输出：
	     * Console: Uncaught TypeError: Object [object Object] has no method 'toString'
	     * 
	     * @throw 
	     * @return void
	     */
	    @JavascriptInterface
	    public void showToast(String toast) {
	        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
	    }
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_web);
		
		btnLoad = findViewById(R.id.btnLoad);
		btnLoad.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				load();
			}
		});

		btnLoadBySys = findViewById(R.id.btnLoadBySys);
		btnLoadBySys.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				loadAsSys();
			}
		});

		btnDown = findViewById(R.id.btnDown);
		btnDown.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mWebView.loadUrl(URL_DOWNLOAD);
			}
		});

		mWebView = (WebView)findViewById(R.id.web);
		mWebView.setVisibility(View.VISIBLE);

		initWebView();

		btnLoadPage = findViewById(R.id.btnLoadPage);
		btnLoadPage.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mWebView.clearFormData();
				mWebView.clearCache(true);
				mWebView.clearHistory();
				mWebView.clearMatches();
				mWebView.clearView();
				mWebView.clearSslPreferences();
				mWebView.loadUrl(URL_LOAD);
			}
		});
		//clickAndScheduleClick();
	}
	
	private void initWebView(){
		WebSettings webSettings = mWebView.getSettings();
		webSettings.setJavaScriptEnabled(true); 
		webSettings.setBuiltInZoomControls(true);
		mWebView.addJavascriptInterface(new JavaScriptInterface(this), "android");

		// 卧槽使用chrome客户端可以跳转app了
		//mWebView.setWebViewClient(new MyWebViewClient(this));
		mWebView.setWebChromeClient(new WebChromeClient());

		/**
		 * 通过系统下载APK
		 */
		mWebView.setDownloadListener(new DownloadListener() {
			@Override
			public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
				Uri uri = Uri.parse(url);
				Intent intent = new Intent(Intent.ACTION_VIEW,uri);
				startActivity(intent);
			}
		});
	}

	private void load(){
		// 加载asset文本
//		String htmlText = AssetUtil.getFromAssets(this, "a.html");
//		mWebView.loadData(htmlText, "text/html", "utf-8");

		// 加载asset中的HTML文件
		mWebView.loadUrl("file:///android_asset/a.html");

		// 加载外部HTML文件
		//mWebView.loadUrl("content://com.android.htmlfileprovider/sdcard/a.html");

		//mWebView.loadUrl("file:///sdcard/a.html");
	}

	private void loadAsSys(){
		Intent intent=new Intent();
		intent.setAction("android.intent.action.VIEW");
		//Uri uri = Uri.parse("content://com.android.htmlfileprovider/sdcard/a.html");
		//Uri uri = Uri.parse("file:///android_asset/a.html");
		Uri uri = Uri.parse("file:///sdcard/a.html");
		//Uri uri = Uri.parse("http://www.qq.com");
		//Uri uri = Uri.parse("https://doctorappapi.91160.com/api.php?c=utility&a=testLiftUpApp&token=8222051b9cadd0ab4569423541f7640c");
		intent.setData(uri);
		intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
		//https://doctorappapi.91160.com/api.php?c=utility&a=testLiftUpApp&token=8222051b9cadd0ab4569423541f7640c

		// 总有一个是可以的
		try{
			intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
		}catch (Exception e){
			try {
				intent.setComponent(new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"));
			}catch (Exception e2){
			}
		}

		startActivity(intent);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private void clickAndScheduleClick(){
		btnLoadPage.performClick();
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				clickAndScheduleClick();
			}
		}, 300);
	}
}
